import * as React from 'react';
import { Select, DatePicker } from 'antd';
import moment from 'moment';
import SpeedTable from '../../component/speedTable';
import { useSpeed } from '../../hook/speed';
import { speedType } from '../../hook/common';
import { useBusinessList } from '../../hook/businessList';
import QueryFormSpeed from '../../component/realtime-fetch-speed-select';
import { setLastSelect } from '../../common/utils';
import Overview from '../../component/speed-data-overview';
import { api } from '../../common/api';
import { collectRequestTimes } from './utils';
import { calcCityDistributionSeriseData } from '../static-speed/calc';
import SlowCgi from './slow-cgi';
import './index.less';

const { useState, useEffect, useMemo } = React;

export default function Log(props) {
    let [speed, setSpeed, getSpeed, timeGranularity, speedLoading] = useSpeed([]);
    const [loading, setLoading] = useState(true);
    const [selectDate, setSelectDate] = useState(moment().add(-1, 'days').format("YYYY-MM-DD"));
    const [list, projectId, setProjectId] = useBusinessList(0);
    const [successRate, setSuccessRate] = useState(0);
    const [successRateCompare, setSuccessRateCompare] = useState(0);
    // 请求次数
    const [requestTimes, setRequestTimes] = useState(0);
    const [requestTimesCompare, setRequestTimesCompare] = useState(0);
    // ALL DATA AVG
    const [avgSpeed, setAvgSpeed] = useState(0);
    const [avgSpeedCompare, setAvgSpeedCompare] = useState(0);
    const [distribution, setDistribution] = useState([]);
    function setSelectProjectId(id) {
        setSpeed([]);
        setProjectId(id);
        setLastSelect(id);
    }

    function changeDate(date, dateString) {
        setSelectDate(dateString);
    }
    useEffect(() => {
        setLoading(true);
        async function fetchData() {
            // 获取选中日期n天前的数据 
            const fetchNDaysAgoDate = n => {
                return api({
                    method: 'GET',
                    url: `speed-server/${projectId}/fetch-daily`,
                    params: {
                        date: moment(selectDate).add(n, 'days').format("YYYY-MM-DD")
                    }
                }) as any;
            }
            // 选中日期一天前和两天前的数据
            const [dayOneData, dayTwoData] = await Promise.all([fetchNDaysAgoDate(0), fetchNDaysAgoDate(-1)]);
            const [dayOneRequestTimes, dayOneSuccessRate] = collectRequestTimes(dayOneData.status || {});
            const [dayTwoRequestTimes, dayTwoSuccessRate] = collectRequestTimes(dayTwoData.status || {});
            const requestTimesCompare = (dayOneRequestTimes - dayTwoRequestTimes) / dayOneRequestTimes;
            setRequestTimes(dayOneRequestTimes);
            setRequestTimesCompare(requestTimesCompare);
            setAvgSpeed(dayOneData.speed)
            setAvgSpeedCompare((dayOneData.speed - dayTwoData.speed) / dayOneData.speed);
            setSuccessRate(dayOneSuccessRate);
            setSuccessRateCompare((dayOneSuccessRate - dayTwoSuccessRate) / dayOneSuccessRate);
            const seriesData = calcCityDistributionSeriseData(dayOneData.distribution);
            setDistribution(seriesData);
            setLoading(false);
        }
        fetchData();
    }, [projectId, selectDate]);
    return (
        <div className="fetch-speed">
            <span>项目选择：</span><Select
                showSearch
                value={projectId}
                onSelect={setSelectProjectId}
                filterOption={(input, option: any) =>
                    option.props.value.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                    option.props.title.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                style={{ width: 260, marginRight: 30 }}
            >
                {
                    list.map((item) => {
                        return (
                            <Select.Option key={item.id.toString()} value={item.id} title={item.name}>
                                {item.id}.{item.name}
                            </Select.Option>
                        )
                    })
                }
            </Select>
            <h3 className="first-title">实时数据分析</h3>
            <QueryFormSpeed onSummit={getSpeed} type={speedType.FETCH} projectId={projectId} />
            <SpeedTable statics={speed} timeGranularity={timeGranularity} speedLoading={speedLoading} />
            <h3 className="first-title">数据分析日报</h3>
            <DatePicker
                onChange={changeDate}
                disabledDate={date => date > moment()}
                defaultValue={moment().add(-1, 'days')}
            ></DatePicker>
            <h3 className="section-title">数据概览</h3>
            {
                useMemo(
                    () => <Overview
                        loading={loading}
                        successRate={successRate}
                        successRateCompare={successRateCompare}
                        avg={avgSpeed}
                        avgCompare={avgSpeedCompare}
                        requestTimes={requestTimes}
                        requestTImesCompare={requestTimesCompare}
                        seriesData={distribution}
                    ></Overview>, [loading])
            }
            <h3 className="section-title">当日CGI追踪</h3>
            <SlowCgi
                projectId={projectId}
                selectDate={selectDate}
            ></SlowCgi>
        </div>
    );
}
